package com.example.xm.controller;

import com.example.xm.entity.Admin;
import com.example.xm.entity.User;
import com.example.xm.entity.dto.UserDto;
import com.example.xm.mapper.UserMapper;
import com.example.xm.service.IUserService;
import com.example.xm.utils.JWTUtils;
import com.example.xm.web.Result;
import com.github.pagehelper.PageInfo;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@Api(tags = "用户模块")
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    IUserService userService;
    @Autowired
    UserMapper userMapper;
    @PostMapping("/reg")
    public Result reg(@RequestBody User user){
        System.out.println("user"+user);
        userService.reg(user);
        return Result.success();
    }
    @PostMapping("/login")
    public Result login(@RequestBody User user){
//        System.out.println(account+"=========="+password);
        String token = userService.login(user.getName(), user.getPassword(),user.getType());
        return Result.success(token);

    }
    @PostMapping("/weblogin")
    public Result weblogin(@RequestBody User user){
//        System.out.println(account+"=========="+password);
        User token = userService.weblogin(user.getName(), user.getPassword(),user.getType());
        return Result.success(token);

    }
    @PostMapping("/update")
    public Result update(@RequestBody User user){
//        System.out.println(account+"=========="+password);
      userService.update(user);
        return Result.success();
    }
    @GetMapping("/getUSer")
    public Result getUSer (Integer uid){
        User user = userMapper.selectByPrimaryKey(uid);
        return Result.success(user);
    }
    @GetMapping("/getUSerInfo")
    public Result getUSerInfo (@RequestHeader("token") String token){
       try {
           Claims parse = JWTUtils.parse(token);
           Integer id =(Integer) parse.get("id");
           User user = userMapper.selectByPrimaryKey(id);
        return Result.success(user);
       }catch (Exception e){
           return Result.fail(500,"token过期");
       }

    }
    @GetMapping("/list")
    public Result list(UserDto dto){
        PageInfo<User> pageInfo= userService.list(dto);
        return Result.success(pageInfo);
    }
    @DeleteMapping("/delete/{ids}")
    public Result delete(@PathVariable String ids){
        String[] split = ids.split(",");
        int[] intArray = new int[split.length];
        for (int i = 0; i < split.length; i++) {
            intArray[i] = Integer.parseInt(split[i]);
        }
        userService.delete(intArray);
        return Result.success();
    }
}
